package cn.fudong.bos.service.take_delivery.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.fudong.bos.dao.base.AreaRepository;
import cn.fudong.bos.dao.base.FixedAreaRepository;
import cn.fudong.bos.dao.take_delivery.WorkBillRepository;
import cn.fudong.bos.domain.base.Area;
import cn.fudong.bos.domain.base.Courier;
import cn.fudong.bos.domain.base.FixedArea;
import cn.fudong.bos.domain.base.SubArea;
import cn.fudong.bos.domain.constant.Constants;
import cn.fudong.bos.domain.take_delivery.Order;
import cn.fudong.bos.domain.take_delivery.WorkBill;
import cn.fudong.bos.service.take_delivery.OrderService;
import cn.fudong.bos.dao.take_delivery.OrderRepository;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private FixedAreaRepository fixedAreaRepository;

	@Autowired
	private OrderRepository orderRepository;

	@Autowired
	private AreaRepository areaRepository;

	@Autowired
	private WorkBillRepository workBillRepository;
	@Autowired
	private JmsTemplate jmsTemplate;

	// 保存订单
	@Override
	public void saveOrder(Order order) {

		// 设置下单时间
		order.setOrderTime(new Date());
		// 设置订单号
		order.setOrderNum(UUID.randomUUID().toString());
		// 设置订单订单状态status 为 1 待取件
		order.setStatus("1");

		// 设置发送地址
		Area sendArea = order.getSendArea();
		Area PersistSendArea = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(),
				sendArea.getCity(), sendArea.getDistrict());
		order.setSendArea(PersistSendArea);

		// 设置收货地址
		Area recArea = order.getSendArea();
		Area PersistRecArea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(),
				recArea.getDistrict());
		order.setRecArea(PersistRecArea);

		// 处理分单业务
		// 1.通过客户的地址信息去查询//
		String FixedAreaId = WebClient.create(Constants.CRM_MANAGEMENT_URL
				+ "/services/customerService/customer/findFixedAreaIdByAddress?address=" + order.getSendAddress())
				.accept(MediaType.APPLICATION_JSON).get(String.class);
		if (FixedAreaId != null) {
			// 如果能查到地址相同的定区，将定区查出来
			FixedArea fixedArea = fixedAreaRepository.findOne(FixedAreaId);
			// 从定区去随机找到一个快递员
			Courier courier = fixedArea.getCouriers().iterator().next();
			if (courier != null) {
				System.out.println("自动分单成功。。。");
				saveOrder(order, courier);
				// 生成工单,给快递员发短息
				addWorkBill(order, courier);
				return;
			}
		}

		// 2.通过客户提交的省市区去遍历改区的所有分区，如果详细地址包含分区名称中的关键字，我们

		Set<SubArea> subareas = PersistSendArea.getSubareas();
		for (SubArea subArea : subareas) {
			if (order.getSendAddress().contains(subArea.getKeyWords())) {
				// 如果详细地址包含分区名称中的关键字,通过该分区找到定区
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						System.out.println("自动分单成功。。。");
						saveOrder(order, courier);
						// 生成工单,给快递员发短息
						addWorkBill(order, courier);

						return;
					}

				}

			}
		}

		for (SubArea subArea : subareas) {
			if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				// 如果详细地址包含分区名称中的关键字,通过该分区找到定区
				FixedArea fixedArea = subArea.getFixedArea();
				// 从定区去随机找到一个快递员
				Courier courier = fixedArea.getCouriers().iterator().next();
				if (courier != null) {
					System.out.println("自动分单成功。。。");
					saveOrder(order, courier);

					// 生成工单,给快递员发短息
					addWorkBill(order, courier);

					return;
				}

			}
		}

		// 人工分单
		order.setOrderType("2");
		orderRepository.save(order);
	}

	// 自动分单方法抽取
	private void saveOrder(Order order, Courier courier) {
		order.setCourier(courier);
		// 将分单类型orderType 设置为 1 自动分单
		order.setOrderType("1");
		// 保存订单
		orderRepository.save(order);
	}

	// 发送短信方法抽取
	private void sendSms(Order order, String smsNumber) {
		jmsTemplate.send("fudong_courier_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("courierTelephone", order.getCourier().getTelephone());// 短信序号
				mapMessage.setString("smsNumber", smsNumber);// 短信序号
				mapMessage.setString("sendAddress", order.getSendAddress());// 取件地址
				mapMessage.setString("sendMobile", order.getSendMobile());// 联系人手机
				mapMessage.setString("remark", order.getRemark());// 给快递员捎话
				return mapMessage;
			}

		});
	}

	// 生成工单方法抽取
	private void addWorkBill(Order order, Courier courier) {
		WorkBill workBill = new WorkBill();
		/** 工单类型 新,追,销 */
		workBill.setType("新");
		/** 取件状态 */
		workBill.setPickstate("新单");
		/** 工单生成时间 */
		workBill.setBuildtime(new Date());
		/** 订单备注 */
		workBill.setRemark(order.getRemark());
		/** 短信序号 */
		String smsNumber = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(smsNumber);
		// 关联快递员，关联运单
		workBill.setOrder(order);
		workBill.setCourier(order.getCourier());
		workBillRepository.save(workBill);
		// 发送短信
		sendSms(order, smsNumber);
		// 修改工单单状态
		workBill.setPickstate("已通知");
	}
	
	
	@Override
	public Order findByOrderNum(String orderNum) {
		
		return orderRepository.findByOrderNum(orderNum);
	}

}
